<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="游泳馆" prop="swimPlaceId">
        <el-select
          v-model="queryParams.swimPlaceId"
          clearable
          placeholder="请选择"
          @change="handleQuery"
        >
          <el-option
            v-for="dict in swimPlaceOptions"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="课程分类" prop="categoryId">
        <el-tree-select
          v-model="queryParams.categoryId"
          :data="categoryOptions"
          :props="{ value: 'id', label: 'name', children: 'children' }"
          value-key="id"
          placeholder="请选择"
          @change="handleQuery"
          check-strictly
        />
      </el-form-item>
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['course:course:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseList">
      <!-- <el-table-column type="index" label="序号" width="60" align="center" /> -->
      <el-table-column label="游泳馆名称" align="center" prop="swimPlaceName" />
      <el-table-column label="课程封面" align="center">
        <template #default="scope">
          <ImagePreview
            :src="scope.row.coverUrl"
            :height="40"
            :width="40"
          ></ImagePreview>
        </template>
      </el-table-column>
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="课程分类" align="center" prop="categoryName" />
      <el-table-column label="限制人数" align="center">
        <template #default="scope"> {{ scope.row.limitNum || 0 }} 人 </template>
      </el-table-column>
      <el-table-column label="报名人数" align="center">
        <template #default="scope">
          {{ scope.row.signupNum || 0 }} 人
        </template>
      </el-table-column>
      <el-table-column
        label="游泳课班级"
        align="center"
        prop="swimPlaceClassName"
      />
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="报名时间" align="center" width="180">
        <template #default="scope">
          <span
            >{{
              parseTime(scope.row.signupStartTime, "{y}-{m}-{d} {h}:{i}:{s}")
            }}
            ~
            {{
              parseTime(scope.row.signupEndTime, "{y}-{m}-{d} {h}:{i}:{s}")
            }}</span
          >
        </template>
      </el-table-column>
      <el-table-column label="上课日期" align="center" width="150">
        <template #default="scope">
          <span
            >{{ parseTime(scope.row.courseStartDate, "{y}-{m}-{d}") }} ~
            {{ parseTime(scope.row.courseEndDate, "{y}-{m}-{d}") }}</span
          >
        </template>
      </el-table-column>
      <el-table-column label="上课时间" align="center" width="180">
        <template #default="scope">
          <span
            >{{ scope.row.courseStartTime }} ~
            {{ scope.row.courseEndTime }}</span
          >
        </template>
      </el-table-column>

      <el-table-column label="排序" align="center" prop="sortNum" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="180"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['course:course:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['course:course:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程对话框 -->
    <el-dialog :title="title" v-model="open" width="780px" append-to-body>
      <el-form ref="courseRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="游泳馆" prop="swimPlaceId">
          <el-select v-model="form.swimPlaceId" clearable placeholder="请选择">
            <el-option
              v-for="dict in swimPlaceOptions"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程分类" prop="categoryId">
          <el-tree-select
            v-model="form.categoryId"
            :data="categoryOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            value-key="id"
            placeholder="请选择"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="form.courseName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="课程老师" prop="courseTeacher">
          <el-input v-model="form.courseTeacher" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="课程封面" prop="coverUrl">
          <image-upload title="课程封面" v-model="form.coverUrl" :limit="1" />
        </el-form-item>
        <el-form-item label="课程描述" prop="courseDesc">
          <el-input
            v-model="form.courseDesc"
            type="textarea"
            :rows="3"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="课程介绍" prop="courseIntro" 
            v-if="richTextShow">
          <editor
            v-model="form.courseIntro"
            :min-height="192"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sortNum">
          <el-input-number
            v-model="form.sortNum"
            :min="1"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="报名时间" prop="times">
          <el-date-picker
            clearable
            v-model="form.times"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item label="上课日期" prop="dates">
          <el-date-picker
            clearable
            v-model="form.dates"
            type="daterange"
            value-format="YYYY-MM-DD"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="上课开始时间">
          <el-input
            style="width: 220px"
            clearable
            v-model="form.courseStartTime"
            value-format="HH:mm"
            placeholder="08:30"
          />
        </el-form-item>
        <el-form-item label="上课截止时间">
          <el-input
            style="width: 220px"
            clearable
            v-model="form.courseEndTime"
            value-format="HH:mm"
            placeholder="20:00"
          />
        </el-form-item>

        <el-form-item label="游泳课班级" prop="swimPlaceClassName">
          <el-input v-model="form.swimPlaceClassName" placeholder="请输入" />
        </el-form-item>

        <el-form-item label="限制人数" prop="limitNum">
          <el-input-number
            v-model="form.limitNum"
            :min="1"
            placeholder="请输入"
          />
        </el-form-item>

        <!-- <el-form-item label="省id" prop="provinceId">
          <el-input v-model="form.provinceId" placeholder="请输入省id" />
        </el-form-item>
        <el-form-item label="省名称" prop="provinceName">
          <el-input v-model="form.provinceName" placeholder="请输入省名称" />
        </el-form-item>
        <el-form-item label="市id" prop="cityId">
          <el-input v-model="form.cityId" placeholder="请输入市id" />
        </el-form-item>
        <el-form-item label="市名称" prop="cityName">
          <el-input v-model="form.cityName" placeholder="请输入市名称" />
        </el-form-item>
        <el-form-item label="区id" prop="areaId">
          <el-input v-model="form.areaId" placeholder="请输入区id" />
        </el-form-item>
        <el-form-item label="区名称" prop="areaName">
          <el-input v-model="form.areaName" placeholder="请输入区名称" />
        </el-form-item> -->
        <el-form-item label="上课地址" prop="address">
          <el-input
            v-model="form.address"
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Course">
import {
  listCourse,
  getCourse,
  delCourse,
  addCourse,
  updateCourse,
} from "@/api/course/course";

import { listCourseCategory } from "@/api/course/courseCategory";

import { listSwimPlace } from "@/api/course/swimPlace.js";

const { proxy } = getCurrentInstance();

const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const checkSignupTime = (rule, value, callback) => {
  if (!form.value.times || form.value.times.length === 0) {
    return callback(new Error("报名时间不能为空"));
  }
  callback();
};

const checkCourseDate = (rule, value, callback) => {
  if (!form.value.dates || form.value.dates.length === 0) {
    return callback(new Error("上课日期不能为空"));
  }
  if (
    new Date(form.value.dates[0]).getTime() <
    new Date(form.value.times[1]).getTime()
  ) {
    return callback(new Error("上课开始日期不能小于报名截止时间"));
  }
  callback();
};

const courseList = ref([]);
const open = ref(false);
const richTextShow = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    swimPlaceId: null,
    categoryId: null,
    courseName: null,
    status: null,
  },
  rules: {
    swimPlaceId: [
      { required: true, message: "游泳馆不能为空", trigger: "blur" },
    ],
    categoryId: [
      { required: true, message: "课程分类不能为空", trigger: "blur" },
    ],
    courseName: [
      { required: true, message: "课程名称不能为空", trigger: "blur" },
    ],
    sortNum: [{ required: true, message: "排序不能为空", trigger: "change" }],
    status: [{ required: true, message: "状态不能为空", trigger: "change" }],
    times: [{ required: true, validator: checkSignupTime, trigger: "change" }],
    dates: [{ required: true, validator: checkCourseDate, trigger: "change" }],
    swimPlaceClassName: [
      { required: true, message: "游泳课班级不能为空", trigger: "change" },
    ],
    limitNum: [
      { required: true, message: "限制人数不能为空", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询课程列表 */
function getList() {
  loading.value = true;
  listCourse(queryParams.value).then((response) => {
    courseList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  richTextShow.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    swimPlaceId: null,
    categoryId: null,
    courseName: null,
    courseTeacher: null,
    coverUrl: null,
    courseDesc: null,
    courseIntro: null,
    sortNum: 1,
    status: "0",
    createBy: null,
    createId: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    delFlag: null,
    dates: null,
    courseStartDate: null,
    courseEndDate: null,
    courseStartTime: null,
    courseEndTime: null,
    times: null,
    signupStartTime: null,
    signupEndTime: null,
    swimPlaceClassName: null,
    limitNum: null,
    provinceId: null,
    provinceName: null,
    cityId: null,
    cityName: null,
    areaId: null,
    areaName: null,
    address: null,
  };
  proxy.resetForm("courseRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  richTextShow.value = true;
  open.value = true;
  title.value = "添加课程";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getCourse(_id).then((response) => {
    const data = response.data || [];
    if (data.courseStartDate && data.courseEndDate) {
      data["dates"] = [data.courseStartDate, data.courseEndDate];
    }
    if (data.signupStartTime && data.signupEndTime) {
      data["times"] = [data.signupStartTime, data.signupEndTime];
    }
    form.value = response.data;
    richTextShow.value = true;
    open.value = true;
    title.value = "修改课程";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["courseRef"].validate((valid) => {
    if (valid) {
      if (form.value.times && form.value.times.length === 2) {
        form.value.signupStartTime = form.value.times[0];
        form.value.signupEndTime = form.value.times[1];
      }
      if (form.value.dates && form.value.dates.length === 2) {
        form.value.courseStartDate = form.value.dates[0];
        form.value.courseEndDate = form.value.dates[1];
      }
      if (form.value.id != null) {
        updateCourse(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCourse(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除该课程？')
    .then(function () {
      return delCourse(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

const categoryOptions = ref([]);
/** 查询课程分类下拉树结构 */
function getTreeselect() {
  listCourseCategory().then((response) => {
    categoryOptions.value = [];
    const data = { id: 0, name: "顶级节点", children: [] };
    data.children = proxy.handleTree(response.data, "id", "parentId");
    categoryOptions.value.push(data);
  });
}

const swimPlaceOptions = ref([]);
function getSwimPlaceList() {
  listSwimPlace({ pageNum: 1, pageSize: 99 }).then((response) => {
    swimPlaceOptions.value = response.rows || [];
  });
}

getTreeselect();

getSwimPlaceList();

getList();
</script>
